package com.wisdytech.linkdcs.account.action;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.bean.StandardTableResult;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.ResourceMatchingService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.DateUtil;
import com.wisdytech.linkdcs.account.model.EquipDocument;
import com.wisdytech.linkdcs.account.model.TtEqDocument;
import com.wisdytech.linkdcs.account.service.ITmDocumentService;
import com.wisdytech.linkdcs.system.model.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * 电子资料控制层controller
 * @author zhanghailin
 *
 */
@Controller
@RequestMapping("/equipment/document")
public class ElectronicDocumentAction {

    @Value("${img.localtion}")
    private String fileLocation;

    @Resource
    private ITmDocumentService tmDocumentService;
    @Autowired
    @Qualifier("resourceMatchingService")
    private ResourceMatchingService resourceMatchingService;
    /**
     *
     * <p>Description: 设备信息</p>
     * @param model model
     * @return String
     */
    @RequestMapping("/index")
    public String electronicDocumentIndex(Model model,HttpServletRequest httpRequest){
        this.resourceMatchingService.getResourceName(httpRequest,model);
        return "platformAccount/electronicDocument";
    }

    /**
     *
     * @param equipCode 设备编码
     * @param equipName 设备名称
     * @param documentName 文档名称
     * @param filter 分页参数
     * @return StandardTableResult
     */
    @RequestMapping(value = "/listDocumentByFilter/get.mvc")
    @ResponseBody
    public StandardTableResult<Map<String, Object>> listDocumentByFilter(String equipCode, String equipName, String documentName, Filter filter) {
        PageInfo<Map<String, Object>> page = this.tmDocumentService.listDocumentByFilter(equipCode,equipName,documentName,filter);
        return new StandardTableResult<>(page.getTotal(),page.getList());
    }
    
    /**
    *
    * @param equipCode 设备编码
    * @param filter 分页参数
    * @return StandardTableResult
    */
   @RequestMapping(value = "/listFileByFilter/get.mvc")
   @ResponseBody
   public StandardTableResult<EquipDocument> listFileByFilter(String fileId,Filter filter) {
       PageInfo<EquipDocument> page = this.tmDocumentService.listFileByFilter(fileId,filter);
       return new StandardTableResult<>(page.getTotal(),page.getList());
   }

    /**
     * @param pkId 
     * @return StandardResult
     */
    @RequestMapping(value = "/getDocumentInById/get.mvc")
    @ResponseBody
    public StandardResult getDocumentInById(String pkId,Filter filter) {
        Map<String, Object> documentInfo = tmDocumentService.getDocumentInById(pkId);
        //获取文件
        PageInfo<EquipDocument> page = this.tmDocumentService.listFileByFilter(pkId,filter);
        List<EquipDocument> list = page.getList();
        documentInfo.put("fileList", list);
        return StandardResult.getSuccessResult(documentInfo);
    }

    /**
     *
     * @param ttEqDocument 实体类
     * @return StandardResult
     */
    @RequestMapping(value = "/saveOrUpdateDocument/save.mvc")
    @ResponseBody
    public StandardResult saveOrUpdateDocument(@RequestBody TtEqDocument ttEqDocument) {
        SysUser user = BaseUtil.getCurrentUser();
        this.tmDocumentService.saveOrUpdateDocument(ttEqDocument,user);
        return StandardResult.getSuccessResult();
    }

    /**
     *
     * @param pkIds 主键
     * @return StandardResult
     */
    @RequestMapping(value = "/deleteDocumentById/del.mvc")
    @ResponseBody
    public StandardResult deleteDocumentById(String pkIds) {
        this.tmDocumentService.deleteDocument(pkIds);
        return StandardResult.getSuccessResult();
    }

    /**
     * <p>Description: 保存设备对象</p>
     * @param file 设备对象
     * @param request 请求对象
     * @return 处理结果对象
     */
    @RequestMapping(value = "/uploadFile/save.mvc")
    @ResponseBody
    public JSONObject savePhoto(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        if(!file.isEmpty()){
            //文件位置存放在tomcat webapp根目录
            //String rootPath = request.getSession().getServletContext().getRealPath("/")+"document/";
            String rootPath = fileLocation+"/document/";
            String originalFilename = file.getOriginalFilename();
            //文件初始名
            String fileName = file.getOriginalFilename();
            //文件扩展名
            String extendName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            //文件重命名
            String realName = BaseUtil.getUUID()+extendName;
            //文件夹名
            String dirName =  DateUtil.getCurDateDefaultStr()+"/";

            File targetFile = new File(rootPath+dirName, realName);

            if(!targetFile.getParentFile().exists()){
                 targetFile.getParentFile().mkdirs();
            }
            //保存
            JSONObject result = new JSONObject();
            result.put("filePath", "document/"+dirName+realName);
            result.put("originalFileName", originalFilename);
            //文件大小单位KB
            long fileSize = file.getSize()/1000;
            if(fileSize==0L) {
                fileSize = 1L;
            }
            result.put("fileSize", fileSize);
            result.put("fileName",realName);
            try {
                file.transferTo(targetFile);
                return result;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new JSONObject();
    }

    /**
     *
     * <p>Description: 下载文件</p>
     * @param pkId 主键
     * @param response 返回
     */
    @RequestMapping(value = "/downloadFile/get.mvc")
    @ResponseBody
    public void download(String pkId, HttpServletRequest request,HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            //查询文件
        	EquipDocument document = this.tmDocumentService.getDocumentInfoById(pkId);
            //
            String originalFileName = document.getOriginalFileName();
            String filePath = document.getFilePath();
            response.setContentType("application/x-download");
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(originalFileName.getBytes("gb2312"), "ISO8859-1"));
            response.setCharacterEncoding("iso-8859-1");
            //设置header jquery 捕获成功标志
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            //String rootPath = request.getSession().getServletContext().getRealPath("/")+"document/";
            String rootPath = fileLocation+"/";
            InputStream inputStream = new FileInputStream(new File(rootPath+filePath));
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("系统异常");
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
    *
    * @param pkIds 主键
    * @return StandardResult
    */
   @RequestMapping(value = "/filedel/del.mvc")
   @ResponseBody
   public StandardResult filedel(String pkId) {
       this.tmDocumentService.filedel(pkId);
       return StandardResult.getSuccessResult();
   }
 
  
}
